﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Caifu.Clients;
using Itfort.Net;
using Caifu.Pres.Datas;

namespace Caifu.Spiders
{
	/// <summary>
	/// 从易天富抓取。
	/// http://www.etf88.com/pm/
	/// </summary>
	public class GetEtf88
	{
		/// <summary>
		/// 运行任务。
		/// </summary>
		public static void RunSpider(DateTime date)
		{
			(new GetEtf88()).Crawl(date);
		}

		void Crawl(DateTime date)
		{
			string nvUrl = "http://www.etf88.com/pm/jzhc.php?sortdate=" + date.ToString("yyyy-MM-dd");
			var html = HttpClient.GetHtml(nvUrl, "gb2312");
			var pattern = @"<td><a href='/jj/[\s\S]*?/' target=_blank>(?<code>[\s\S]*?)</a></td><td><a href='/jj/[\s\S]*?/' target=_blank>(?<name>[\s\S]*?)</a></td><td>([\s\S]*?)</td><td>(?<date>[\s\S]*?)</td><td>(?<unv>[\s\S]*?)</td><td>(?<anv>[\s\S]*?)</td>";
			var matchs = Regex.Matches(html, pattern);

			if (matchs.Count == 0)
			{
				// 报告问题
			}

			foreach (Match match in matchs)
			{
				try
				{
					var tdate = DateTime.Parse(match.Groups["date"].Value);
					// 目标与期望不符
					if (tdate != date) continue;

					var fundCode = match.Groups["code"].Value;

					var fundInfo = FundUtil.GetFundByAnyCode(fundCode);
					Guid fundId = Guid.Empty;
					if (fundInfo != null)
					{
						fundId = fundInfo.Id;
						fundCode = fundInfo.Code;
					}

					var unv = Decimal.Parse(match.Groups["unv"].Value);
					var anv = Decimal.Parse(match.Groups["anv"].Value);

					var pnv = NetValuePreClient.GetNetValuePre(fundCode, date);
					if (pnv == null)
					{
						pnv = new NetValuePre();
						pnv.FundId = fundId;
						pnv.FundCode = fundCode;
						pnv.ReportDate = date;

						pnv.UnitNetValue3 = unv;
						pnv.AccumulatedNetValue3 = anv;

						NetValuePreClient.AddNetValuePre(pnv);
					}
					else
					{
						if (pnv.UnitNetValue3 == null || pnv.UnitNetValue3.Value == 0 ||
							pnv.AccumulatedNetValue3 == null || pnv.AccumulatedNetValue3.Value == 0)
						{
							pnv.UnitNetValue3 = unv;
							pnv.AccumulatedNetValue3 = anv;

							NetValuePreClient.UpdateNetValuePre(pnv);
						}
					}
				}
				catch (Exception ex)
				{
					// 报告错误
					Trace.WriteLine(ex.Message + Environment.NewLine
						+ ex.Source + Environment.NewLine
						+ ex.StackTrace);
				}
			}
		}

		/// <summary>
		/// 采集指定日期的基金净值。
		/// </summary>
		/// <param name="date"></param>
		/// <returns>
		/// 以DataTable格式返回。
		/// FundCode，
		/// ReportDate，
		/// UnitNetValue，
		/// AccumulatedNetValue
		/// </returns>
		public static DataTable CrawlNetValues(DateTime date)
		{
			DataTable table = new DataTable("netvalues");
			table.Columns.Add("FundCode", typeof(string));
			table.Columns.Add("ReportDate", typeof(DateTime));
			table.Columns.Add("UnitNetValue", typeof(decimal));
			table.Columns.Add("AccumulatedNetValue", typeof(decimal));

			string nvUrl = "http://www.etf88.com/pm/jzhc.php?sortdate=" + date.ToString("yyyy-MM-dd");
			var html = HttpClient.GetHtml(nvUrl, "gb2312");
			var pattern = @"<td><a href='/jj/[\s\S]*?/' target=_blank>(?<code>[\s\S]*?)</a></td><td><a href='/jj/[\s\S]*?/' target=_blank>(?<name>[\s\S]*?)</a></td><td>([\s\S]*?)</td><td>(?<date>[\s\S]*?)</td><td>(?<unv>[\s\S]*?)</td><td>(?<anv>[\s\S]*?)</td>";
			var matchs = Regex.Matches(html, pattern);

			if (matchs.Count == 0)
			{
				// 报告问题
			}

			foreach (Match match in matchs)
			{
				var dataRow = table.NewRow();
				dataRow["ReportDate"] = date;

				try
				{
					var tdate = DateTime.Parse(match.Groups["date"].Value);
					// 目标与期望不符
					if (tdate != date) continue;

					var fundCode = match.Groups["code"].Value;
					var unv = Decimal.Parse(match.Groups["unv"].Value);
					var anv = Decimal.Parse(match.Groups["anv"].Value);

					dataRow["FundCode"] = fundCode;
					dataRow["UnitNetValue"] = unv;
					dataRow["AccumulatedNetValue"] = anv;

					table.Rows.Add(dataRow);
				}
				catch (Exception ex)
				{
					// 报告错误
					Trace.WriteLine(ex.Message + Environment.NewLine
						+ ex.Source + Environment.NewLine
						+ ex.StackTrace);
				}
			}

			return table;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="url"></param>
		/// <param name="date"></param>
		/// <returns></returns>
		public static IList<NetValueItem> _Crawl(string url, DateTime date)
		{
			var pattern = @"<td><a href='/jj/[\s\S]*?/' target=_blank>(?<code>[\s\S]*?)</a></td><td><a href='/jj/[\s\S]*?/' target=_blank>(?<name>[\s\S]*?)</a></td><td>([\s\S]*?)</td><td>(?<date>[\s\S]*?)</td><td>(?<unv>[\s\S]*?)</td><td>(?<anv>[\s\S]*?)</td>";
			CommonSipder spider = new CommonSipder();
			spider.Pattern = pattern;
			return spider.Crawl(url, "gb2312", date);
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="date"></param>
		/// <returns></returns>
		public static IList<NetValueItem> _Crawl(DateTime date)
		{
			string url = "http://www.etf88.com/pm/jzhc.php?sortdate=" + date.ToString("yyyy-MM-dd");
			return _Crawl(url, date);
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="date"></param>
		public static void _CrawlAndSave(DateTime date)
		{
			var list = _Crawl(date);
			var preNetValueThirds = Utils.ConvertToPreNetValueThirds(list, "易天富");
			PreNetValueThirdData.Instance.Save(preNetValueThirds);
		}
	}
}
